(function () {
    let chatList = document.querySelector('#chatList')
    let message = document.querySelector("#message")
    let send = document.querySelector("#send")
    let username = localStorage.getItem("username")
    // 实例化WebSocket
    let ws = new WebSocket('ws:localhost:8000')
    const init = () => {
        bindEvent()
    }

    function bindEvent() {
        send.addEventListener('click', handleSendMessageBtn, false)
        ws.addEventListener('open', handleOpen, false)
        ws.addEventListener("close", handleClose, false)
        ws.addEventListener("error", handleError, false)
        ws.addEventListener("message", handleMessage, false)
    }

    function handleSendMessageBtn() {
        // 判断用户是否登录
        if (!username) {
            alert("请先登录再发送消息")
            history.replaceState({},'','entry.html')
            return
        }
        // 发送消息时判断用户是否输入内容
        let msg = message.value.trim() //没有气泡，所以去除前后空格
        if (!msg.length) {
            return
        }

        // 发送消息
        ws.send(JSON.stringify({
            username,
            dataTime: +new Date(),
            message: msg
        }))

    }

    function handleOpen() {
        console.log("websocket聊天室已打开")
    }

    function handleClose() {
        console.log("websocket聊天室已关闭")
    }

    function handleError() {
        console.warn("websocket Error")
    }

    function handleMessage(e) {
        // 接收后端返回的消息
        chatList.appendChild(createItem(JSON.parse(e.data)))
        message.value = ''
    }

    function createItem(data) {
        let li = document.createElement('li')
        li.innerHTML = `
            <p>
                <span>${data.username}</span>
                <i>${new Date(data.dataTime)}</i>
            </p>
            <p>
                <strong>${data.message}</strong>
            </p>
    `
        return li
    }
    init()

})()